var $ = window.$;
var frac = require('../../../util/frac');
var event = require('../../../core/event');
var sound = require('../../audio/sound');
var sample = require('../../sample/manager');
var timing = require('../../timing/manager');
var Log = require('../../../util/logger');


var ret = {
	setUI: function (_ui) {
		this.ui = _ui;
	},

	onCancel: function(){
		//this.select = null;
	},

	onCopy: function(){
	},

	onPaste: function () {
		var select = this.ui.note.find('.curr');
		var selectPad = this.ui.selectedNotes;
		if(!select.size() && $.isEmptyObject(selectPad)){
			Log.i("paste note: 0!!");
			return;
		}
		Log.i("paste note:"+ select.size());

		//1. 当前时间对应的beat值, 对齐栅格
		var beat = this.ui.getGridBottomBeat();
		//2. 找到选中note最小beat值
		var notes = [];
		var len = select.size();
		var _min = [99999999, 0, 1];  //要能比这beat还大我就吃键盘
		for(var i=0;i<len;i++){
			var _id = +select.eq(i).data('tag');
			var _note = this.ui.manager.getNote(_id);
			notes.push(_note); //为了省事, notes和select完全对应
			if(frac.compare(_note.beat, _min) < 0){
				_min = _note.beat;
			}
		}
		for(var _id in selectPad){
			if(!selectPad.hasOwnProperty(_id)){
				continue;
			}
			var _note = this.ui.manager.getNote(_id);
			notes.push(_note);
			if(frac.compare(_note.beat, _min) < 0){
				_min = _note.beat;
			}
		}

		//去掉旧选中
		//this.ui.note.find('.curr').removeClass('curr');
		//3. 计算beat差, 全部note加上这个差值
		var delta = frac.subtract(beat, _min);
		len = notes.length;
		for(var i=0;i<len;i++){
			var _note = this.ui.manager.copyNote(notes[i]);
			_note.beat = frac.add(_note.beat, delta);
			if(_note.endbeat){
				_note.endbeat = frac.add(_note.endbeat, delta);
			}
			var id = this.ui.manager.addNote(_note);
			var time;
			if(_note.index >= 0){
				//用type判断恐怕存在一定概率异常
				time = timing.beatToTime(_note.beat);
				_note.time = time;
				if(_note.endbeat){
					_note.endtime = timing.beatToTime(_note.endbeat);
				}
				this.ui.addTouchNoteDiv(_note, {isHold: !!_note.endbeat});
				this.ui.changeMusicbar(_note.beat, 1);
			}else{
				var html = $('<div data-tag="'+id+'"></div>');
				var color = this.select.eq(i).css('backgroundColor');
				if(color){
					html.css('backgroundColor', color);
				}

				time = timing.beatToTime(_note.beat) + (_note.offset || 0);
				this.ui.note.append(html);
				this.ui.alignNote(_note, html);
			}
			//重载音频
			if(_note.sound){
				_note.tid = sound.addCell(sample.getFilePath(_note.sound), _note.vol || 30, 0);
				if(_note.tid >= 0){
					sound.offsetCell(_note.tid, time);
				}
			}

			this.ui.checkMaxTime(time);
		}
		debugger;
		this.ui.manager.sortNotes();
        this.ui.reInitSeekQueue();
		this.ui.clearEditCanvas();
		this.ui.drawNotes();
		event.trigger(event.events.note.change);
	},

	onCut: function(){

	}
};

module.exports = ret;